/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.json.parser;

import org.zhiqim.kernel.json.JsonParser;
import org.zhiqim.kernel.json.JsonString;
import org.zhiqim.kernel.json.Jsons;

/**
 * 基本类型适配器，8种基本类型&null&字符串
 * 1、char和String在toString时要加引号
 * 2、Fastjson/Jackson仅支持（'true', 'false' or 'null'）,即null和boolean类型的字符串
 * 3、Fastjson/Jackson不支持char/String转为对象，Gson支持，这里采用Gson方案
 *
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class JsonStringParser implements JsonParser
{
    @Override
    public String toString(Object obj)
    {
        JsonString value = (JsonString)obj;
        if (value == null)
            return "null";
        
        String val = value.val();
        if (val == null)
        {//没有值
            return "null";
        }
        else if (!value.escape())
        {//[]{}开头的认为是数据和对象，null/true/false/number等直接返回，不要前置转义符和引号
            return val;
        }
        else
        {//字符串的对需要转义的字符增加前置转义符，再两边加引号
            val = Jsons.addEscapeChar(val, '\"');
            return new StringBuilder("\"").append(val).append("\"").toString();
        }
    }
    
    @Override
    public Object toObject(String json, Class<?> cls)
    {
        if ((json.startsWith("[") && json.endsWith("]")) || (json.startsWith("{") && json.endsWith("}")))
        {//[]{}开头的认为是列表和对象，内容不作转义操作
            return new JsonString(json, false);
        }
        else if (Jsons.isStartEndQuotation(json))
        {//标准字符串的
            String val = Jsons.removeStartEndQuotation(json);
            val = Jsons.removeEscapeChar(val);
            return new JsonString(val, true);
        }
        else
        {//null/true/false/number等不需要转义和引号的
            return new JsonString(json, false);
        }
    }
}
